package com.mall507.fivepeaks.activity.mine;

import android.os.Build;
import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.google.gson.Gson;
import com.hzh.frame.comn.callback.HttpCallBack;
import com.hzh.frame.core.HttpFrame.BaseHttp;
import com.hzh.frame.ui.fragment.AbsRecyclerViewFM;
import com.hzh.frame.widget.rxbus.MsgEvent;
import com.hzh.frame.widget.rxbus.RxBus;
import com.hzh.frame.widget.xdialog.XDialog2Button;
import com.hzh.frame.widget.xrecyclerview.RecyclerViewHolder;
import com.mall507.comn.model.MineRelease;
import com.mall507.comn.model.User;
import com.mall507.comn.tools.UserTools;
import com.mall507.fivepeaks.R;
import com.mall507.fivepeaks.widget.imageview.CircleImageView;
import com.mall507.fivepeaks.widget.imageview.ExpandImageView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import io.reactivex.functions.Consumer;
import io.reactivex.functions.Predicate;

/**
 * @author
 * @version 1.0
 * @date 2019/8/26
 */
@Route(path = "/mine/ReleaseSubRFM")
public class ReleaseSubRFM extends AbsRecyclerViewFM<MineRelease> {
    public static final String TAG="ReleaseSubRFM";

    @Override
    public boolean setTitleIsShow() {
        return false;
    }

    public static ReleaseSubRFM newInstance(int type) {
        ReleaseSubRFM myFragment = new ReleaseSubRFM();
        Bundle bundle = new Bundle();
        bundle.putInt("type", type);
        myFragment.setArguments(bundle);
        return myFragment;
    }

    @Override
    protected int setLayoutId() {
        return R.layout.fm_rv_mine_release_index;
    }

    @Override
    protected void bindView(View view) {
        showLoding();
        super.bindView(view);
        initBus();
    }

    @Override
    protected JSONObject setHttpParams() {
        JSONObject params = new JSONObject();
        try {
            params.put("type", getArguments().getInt("type"));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return params;
    }
    
    @Override
    protected String setHttpPath() {
        return "Me/getRelease";
    }

    @Override
    protected List<MineRelease> handleHttpData(JSONObject response) {
        List<MineRelease> list = new ArrayList<>();
        if(200 == response.optInt("code")){
            JSONArray jsonArray=response.optJSONArray("data");
            if (jsonArray != null&&jsonArray.length()>0){
                for(int i=0;i<jsonArray.length();i++){
                    JSONObject object = jsonArray.optJSONObject(i);
                    MineRelease model = new MineRelease();
                    model.setNid(object.optString("id"));
                    model.setCover_img(object.optString("cover_img"));
                    model.setTitle(object.optString("title"));
                    model.setCreate_at(object.optString("create_at"));
                    model.setContent(object.optString("content"));
                    model.setViews(object.optString("views"));
                    model.setCollection_count(object.optString("collection_count"));
                    model.setBlog_type(object.optString("blog_type"));
                    model.setStatus_name(object.optString("status_name")); //审核状态
                    list.add(model);
                }
            }
        }
        dismissLoding();
        return list;
    }

    @Override
    protected void handleHttpDataFailure() {
        super.handleHttpDataFailure();
        showLodingFail();
    }


    @Override
    protected int setItemLayoutId(int viewType) {
        return R.layout.item_rv_mine_original;
    }

    @Override
    protected void bindItemData(RecyclerViewHolder holder,final int position, final MineRelease model) {
        TextView shenhe = holder.itemView.findViewById(R.id.shenhe);
        Button delete = holder.itemView.findViewById(R.id.delete);
        ((ExpandImageView) holder.getView(R.id.image)).setImageURI(model.getCover_img());
        holder.setText(R.id.title,model.getTitle());
        ((CircleImageView) holder.getView(R.id.head)).setImageURI(model.getHead_img());
        holder.setText(R.id.time,model.getCreate_at());
        holder.setText(R.id.status_time,model.getCreate_at());
        if (model.getContent() != null && model.getContent().length()>0){
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                holder.setText(R.id.content, String.valueOf(Html.fromHtml(model.getContent(),Html.FROM_HTML_MODE_COMPACT)));
            }else {
                holder.setText(R.id.content, String.valueOf(Html.fromHtml(model.getContent())));
            }
        }
        
        holder.setText(R.id.browseNumber,model.getViews()+"人浏览");
        holder.setText(R.id.lickNumber,model.getCollection_count());
        if (UserTools.getInstance().getIsLogin()) {
            User user = UserTools.getInstance().getUser();
            ((CircleImageView) holder.getView(R.id.head)).setImageURI(user.getHead());
            holder.setText(R.id.nice,user.getNickName());
        }else {
            User user = UserTools.getInstance().getUser();
            ((CircleImageView) holder.getView(R.id.head)).setImageURI(user.getHead());
            holder.setText(R.id.nice,user.getNickName());
        }

        holder.setOnItemClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                switch (model.getBlog_type()){
                    case "1":
                        ARouter.getInstance()
                                .build("/comn/ComnCultureItemInfoRUI")
                                .withString("id", model.getNid())
                                .withString("commentRequestPath","Comment/getOriginalComment")
                                .withString("headRequestPath","Original/getOriginDetail")
                                .withString("type","4")
                                .withString("position", position+"")
                                .withString("collection_count",model.getCollection_count())
                                .navigation();
                        break;
                    case "2":
                        ARouter.getInstance()
                                .build("/comn/ComnCultureItemInfoRUI")
                                .withString("id", model.getNid())
                                .withString("commentRequestPath", "Comment/getOriginalComment")
                                .withString("headRequestPath", "Original/getOriginDetail")
                                .withString("type", "5")
                                .withString("position", position+"")
                                .withString("collection_count", model.getCollection_count())
                                .navigation();
                        break;
                }
                
            }
        });
        if (model.getStatus_name() != null && model.getStatus_name().length()>0){
            shenhe.setText(model.getStatus_name());
            switch (model.getStatus_name()){
                case "待审核":
                    shenhe.setTextColor(getResources().getColor(R.color.red));
                    delete.setVisibility(View.INVISIBLE);
                    break;
                case "审核通过":
                    shenhe.setTextColor(getResources().getColor(R.color.base_title_color));
                    delete.setVisibility(View.VISIBLE);
                    break;
                case "审核不通过":
                    shenhe.setTextColor(getResources().getColor(R.color.red));
                    delete.setVisibility(View.VISIBLE);
                    break;
            }
        }
        final JSONObject params = new JSONObject();
        try {
            params.put("type", getArguments().getInt("type"));
            params.put("id", model.getNid());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new XDialog2Button(getActivity()).setMsg("删除\n确定要删除该发布信息？").setCallback(new XDialog2Button.XDialog2ButtonCallBack() {
                    @Override
                    public void confirm() {
                        BaseHttp.getInstance().query("Me/deleteInfo", params, new HttpCallBack() {
                            @Override
                            public void onSuccess(JSONObject response) {
                                super.onSuccess(response);
                                if (response.optInt("code") == 200){
                                    onRefresh();
                                }else {
                                    alert(response.optString("message"));
                                }
                            }
                        });
                    }
                    @Override
                    public void cancel() {}
                }).show();
            }
        });
    }

    public void initBus() {
        RxBus.getInstance()
                .toObservable(getViewLifecycleOwner(), MsgEvent.class)
                .filter(new Predicate<MsgEvent>() {
                    @Override
                    public boolean test(MsgEvent msgEvent) throws Exception {
                        return msgEvent.getTag().equals(TAG);
                    }
                })
                .subscribe(new Consumer<MsgEvent>() {
                    @Override
                    public void accept(MsgEvent msgEvent) throws Exception {
                        String msg= (String) msgEvent.getMsg();
                        HashMap<String,Object> map=new Gson().fromJson(msg, HashMap.class);
                        int position=Integer.parseInt(map.get("position").toString());
                        MineRelease model=getAdapter().getDatas().get(position);
                        model.setCollection_count(map.get("collection").toString());
                        model.setViews(map.get("views").toString());
                        getAdapter().notifyItemChanged(position);
                    }
                });
    }
    
}
